package vip.liux.backend.adapter.controllers;

import jakarta.annotation.Resource;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.liux.backend.adapter.controllers.models.LinkUserLoginInfo;
import vip.liux.backend.adapter.controllers.models.UserLoginInfo;
import vip.liux.backend.application.service.account.AccountAppService;
import vip.liux.backend.application.service.account.dtos.*;

import java.io.File;

@RestController
@RequestMapping("/api/account")
public class AccountInfoController {

    private static final Logger log = LoggerFactory.getLogger(AccountInfoController.class);

    protected static byte[] defaultAvatarContent = null;

    @Resource
    private AccountAppService accountAppService;

    //region Login

    /**
     * 登录
     */
    @PostMapping("/login")
    public void login(@RequestBody UserLoginInfo login) {
        System.out.println("login");
    }

    /**
     * 关联登录
     */
    @PostMapping("/link-login")
    public void linkLogin(@RequestBody LinkUserLoginInfo login) {
        System.out.println("linkLogin");
    }

    /**
     * 登出
     */
    @GetMapping("/logout")
    public void logout() {
    }

    /**
     * 检查密码
     */
    @PostMapping("check-password")
    public void checkPassword(UserLoginInfo login) {
    }

    /**
     * 外部登录
     */
    @PostMapping("/external-login")
    public void externalLogin(String provider) {
        System.out.println("externalLogin");
    }

    //endregion

    //region Account

    /**
     * 注册新用户
     */
    @PostMapping("/register")
    public void register(@RequestBody RegisterDto input) {
        accountAppService.register(input);
    }

    /**
     * 发送密码重置码
     */
    @PostMapping("/send-password-reset-code")
    public void sendPasswordResetCode(@RequestBody SendPasswordResetCodeDto input) {

    }

    /**
     * 重置密码
     */
    @PostMapping("/reset-password")
    public void resetPassword(@RequestBody ResetPasswordDto input) {
        // return accountAppService.resetPassword(input);
    }

    /**
     * 发送手机号确认令牌
     */
    @PostMapping("/send-phone-number-confirmation-token")
    public void sendPhoneNumberConfirmationToken(@RequestBody SendPhoneNumberConfirmationTokenDto input) {
        // return accountAppService.sendPhoneNumberConfirmationToken(input);
    }

    /**
     * 发送邮箱确认令牌
     */
    @PostMapping("/send-email-confirmation-token")
    public void sendEmailConfirmationToken(@RequestBody SendEmailConfirmationTokenDto input) {
        // return accountAppService.sendEmailConfirmationToken(input);
    }

    /**
     * 确认手机号
     */
    @PostMapping("/confirm-phone-number")
    public void confirmPhoneNumber(@RequestBody ConfirmPhoneNumberInput input) {
        // return accountAppService.confirmPhoneNumber(input);
    }

    /**
     * 确认邮箱
     */
    @PostMapping("/confirm-email")
    public void confirmEmail(@RequestBody ConfirmEmailInput input) {
        // return accountAppService.confirmEmail(input);
    }

    /**
     * 设置用户头像
     */
    @PostMapping("/profile-picture")
    public void setProfilePicture(ProfilePictureInput input) {
        // accountAppService.setProfilePicture(input);
        // return ResponseEntity.ok().build();
    }

    /**
     * 根据ID获取用户头像
     *
     * @param id 头像ID
     * @return 用户头像
     */
    @GetMapping("/profile-picture/{id}")
    public ProfilePictureSourceDto getProfilePicture(@PathVariable("id") Long id) {
        // ProfilePictureSourceDto pictureSource = accountAppService.getProfilePicture(id);
        // if (pictureSource.getType() == ProfilePictureType.NONE) {
        //     pictureSource.setFileContent(getDefaultAvatar());
        // }
        // return ResponseEntity.ok(pictureSource);
        return null;
    }

    /**
     * 发送邮箱安全码
     */
    @PostMapping("/send-email-security-code")
    public void sendEmailSecurityCode(@RequestBody SendEmailSecurityCodeDto input) {
        // return accountAppService.sendEmailSecurityCode(input);
    }

    /**
     * 发送手机安全码
     */
    @PostMapping("/send-phone-security-code")
    public void sendPhoneSecurityCode(@RequestBody SendPhoneSecurityCodeDto input) {
        // return accountAppService.sendPhoneSecurityCode(input);
    }

    /**
     * 上传用户头像文件
     *
     * @param image 头像文件
     */
    @PostMapping("/profile-picture-file")
    public void uploadProfilePictureFile(@RequestParam("image") MultipartFile image) {
        // if (image == null) {
        //     return ResponseEntity.badRequest().build();
        // }
        // ProfilePictureInput input = new ProfilePictureInput();
        // input.setType(ProfilePictureType.IMAGE);
        // input.setImageContent(image.getBytes());
        // accountAppService.setProfilePicture(input);
        // return ResponseEntity.ok().build();
    }

    /**
     * 根据ID获取用户头像文件
     *
     * @param id 头像ID
     * @return 用户头像文件
     */
    @GetMapping("/profile-picture-file/{id}")
    public ResponseEntity<InputStreamResource> getProfilePictureFile(@PathVariable("id") Long id) {
        // ProfilePictureSourceDto pictureSource = accountAppService.getProfilePicture(id);
        // if (pictureSource.getType() == ProfilePictureType.GRAVATAR) {
        //     return ResponseEntity.status(HttpStatus.FOUND).location(URI.create(pictureSource.getSource())).build();
        // }
        // if (pictureSource.getType() == ProfilePictureType.IMAGE) {
        //     return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(pictureSource.getFileContent());
        // }
        // return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(getDefaultAvatar());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", "avatar.jpg");
        headers.setContentType(MediaType.IMAGE_JPEG);
        headers.setContentLength(getDefaultAvatar().length);

        return new ResponseEntity<>(
                new InputStreamResource(new ByteArrayResource(getDefaultAvatar())),
                headers,
                HttpStatus.OK
        );
    }

    /**
     * 获取默认头像
     *
     * @return 默认头像字节数组
     */
    private byte[] getDefaultAvatar() {
        if (defaultAvatarContent == null) {
            try {
                File file = ResourceUtils.getFile("classpath:static/images/default-avatar.jpg");
                defaultAvatarContent = FileUtils.readFileToByteArray(file);
            } catch (Exception e) {
                log.error("Failed to read default avatar", e);
                return new byte[0];
            }
        }
        return defaultAvatarContent;
    }
    //endregion
}